#import "PedidoPrintController.h"
#import <MessageUI/MessageUI.h> 

@interface PedidoPrintController ()<MFMailComposeViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (strong, nonatomic) NSString* html;
@property (nonatomic) BOOL isFirstTime;
@end

@implementation PedidoPrintController

@synthesize pedido;
@synthesize webView;
@synthesize repositoryProvider;
@synthesize html;
@synthesize isFirstTime;

-(void)viewDidLoad {
    [super viewDidLoad];
    self.isFirstTime = YES;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (!self.isFirstTime) {
        return;
    }
    
    self.isFirstTime = NO;
    
    UIBarButtonItem* rightItem = self.navigationItem.rightBarButtonItem;
    UIActivityIndicatorView* spinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    [spinner startAnimating];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:spinner];
    
    dispatch_queue_t queue = dispatch_queue_create("Load Html", NULL);
    dispatch_async(queue, ^() {
        NSError* error;
        self.html = [self.repositoryProvider.searchService getGetPedidoPrintHtml:self.pedido.id error:&error];
        dispatch_async(dispatch_get_main_queue(), ^(){
            [spinner stopAnimating];
            self.navigationItem.rightBarButtonItem = rightItem;
            if (error) {
                [[[UIAlertView alloc] initWithTitle:@"Erro" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
            } else {
                [self.webView loadHTMLString:self.html baseURL:nil];
            }
        });
    });
}

- (IBAction)emailTapped:(id)sender {
    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
    mc.mailComposeDelegate = self;
    [mc setSubject:self.title];
    [mc setMessageBody:self.html isHTML:YES];
    [self presentViewController:mc animated:YES completion:NULL];
}

-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    [self dismissViewControllerAnimated:YES completion:NULL];
}

@end
